<?php


namespace app\api\controller;

use think\Db;
use think\Exception;
use think\Config;

/**
 * Class 交易
 * @package app\api\controller
 */
class Transaction extends \app\common\controller\Api
{
    protected $noNeedLogin = ['k_line','trading_hall','now_info','downsearch'];
    protected $noNeedRight = ['*'];
    /**
     * k_线
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function k_line(){
        $type = input('type',1);//1=cb,2=cc
        $timetype = input('time',1);//1=7天,2=30天,3=90天
        if ($type == 1){
            $table = 'cb_price';
        }elseif($type == 2){
            $table = 'cc_price';
        }else{
            $this->error('别瞎指定啊');
        }
        if ($timetype == 1){
            $num = 7;
        }elseif ($timetype == 2){
            $num = 30;
        }elseif ($timetype == 3){
            $num = 90;
        }else{
            $this->error('别瞎指定啊');
        }
        $list = db($table)
            ->field('price,createtime')
            ->order('id DESC')
            ->limit($num)
            ->select();

        $lose = $num - count($list);
        if ($list){
            $endtime = end($list)['createtime'];
        }else{
            $endtime = time();
        }
        for ($i = 1; $i<= $lose;$i++){
            //补全缺少数据
            $bu = [];
            $bu['price'] = 0;
            $bu['createtime'] = $endtime - $i*24*60*60;
            $list[] = $bu;
        }
        $data = [];
//        $data['time'] = [];
//        $data['price'] = [];
        foreach ($list as $key => $value){
//            $data['time'][] = date('Y-m-d',$value['createtime']);
//            $data['price'][] = $value['price'];
            $data[] = [date('Y-m-d',$value['createtime']),$value['price'],$key];
        }
        $data = array_reverse($data);
        $this->success('ok',$data);
    }

    /**
     * 交易页 cc/cb 信息
     */
    public function now_info(){
        $type = input('type',1);//1=cb,2=cc
        $data = [];
        if ($type == 1){
            $cb_buy_jishu = Config::get('site.cb_want_buy') ??0;//cb求购增加基数
            $cb_sell_jishu = Config::get('site.cb_want_sell')??0;//cb卖出增加基数
            $bi = db('cb_price')->order('id DESC')->find();
            if ($bi){
                $data['price'] = $bi['price'];
            }else{
                $data['price'] = 0;
            }
            $cb_buy = db('buy')->where('status','1')->where('type','1')->sum('num');
            $cb_buy_ok = db('buy')->where('status','2')->where('type','1')->sum('num');
            $data['buy_num'] = $cb_buy + $cb_buy_jishu ;
            $data['buy_num_ok'] = $cb_buy_ok + $cb_sell_jishu;
        }elseif($type == 2){
            $cc_buy_jishu = Config::get('site.cc_want_buy')??0;//cb求购增加基数
            $cc_sell_jishu = Config::get('site.cc_want_sell')??0;//cb卖出增加基数
            $bi = db('cc_price')->order('id DESC')->find();
            if ($bi){
                $data['price'] = $bi['price'];
            }else{
                $data['price'] = 0;
            }
            $cb_buy = db('buy')->where('status','1')->where('type','2')->sum('num');
            $cb_buy_ok = db('buy')->where('status','2')->where('type','2')->sum('num');
            $data['buy_num'] = $cb_buy + $cc_buy_jishu;
            $data['buy_num_ok'] = $cb_buy_ok + $cc_sell_jishu;
        }else{
            $this->error('别瞎指定啊');
        }
        $to_cny = db('config')->where('name','to_cny')->value('value');
        $data['cny'] = round($data['price'] * $to_cny /100,2);
        $this->success('ok',$data);
    }

    /**
     * 交易大厅
     */
    public function trading_hall(){
        $user_id = input('user_id') ? input('user_id'):'';//指定用户
        $type = input('type') ? input('type') :1;//1=cb,2=cc
        $range = input('range') ? input('range'):'';//取值范围,例:1-100
        $list_type = input('list_type') ? input('list_type') :1;//1买入,2=完成
        if (!in_array($type,['1','2'])){
            $this->error('别瞎指定啊');
        }
        if (!in_array($list_type,['1','2'])){
            $this->error('别瞎指定啊');
        }
        $page = input('page') ? input('page'):1;
        $limit = input('limit') ? input('limit'):5;
        if($list_type == 1){
            //买入列表
            $where = [];
            if ($user_id){
                $where['user_id'] = $user_id;
            }
            if ($range){
                $rangearr = explode(' - ',$range);
                $where['num'] = ['between',$rangearr];
            }
            $where['type'] = $type;
            $where['status'] = '1';//挂单中
            $list = model('buy')
                ->with('user')
                ->where($where)
                ->page($page,$limit)
                ->select();
        }else{
            //完成列表
            $user = $this->auth->getUser();
            if ($user->is_truename == 1){
                $this->error('请先通过实名验证');
            }
            $where = [];
            if ($user_id){
                $user->id = $user_id;
            }
            if ($range){
                $rangearr = explode('-',$range);
                $where['num'] = ['between',$rangearr];
            }
            $where['type'] = $type;
            $where['status'] = '3';//完成

            $list = model('order')
                ->with('buyuser')
                ->with('selluser')
                ->where($where)
                ->where('buy_user_id|sell_user_id',$user->id)
                ->order('id DESC')
                ->page($page,$limit)
                ->select();
            $list = collection($list)->toArray();
            foreach ($list as  $key => $value){
                if ($value['sell_user_id'] == $user->id){
                    //自己是卖家
                    $list[$key]['user']['nickname'] = $value['buyuser']['nickname'];
                    $list[$key]['user']['avatar'] = $value['buyuser']['avatar'];
                    $list[$key]['user']['id'] = $value['buyuser']['id'];
                }else{
                    //自己是买家
                    $list[$key]['user']['nickname'] = $value['selluser']['nickname'];
                    $list[$key]['user']['avatar'] = $value['selluser']['avatar'];
                    $list[$key]['user']['id'] = $value['selluser']['id'];
                }
            }
        }
        $data = [];

        foreach ($list as $key => $value){
            $data[$key]['id'] = $value['id'];
            $data[$key]['avatar'] = $value['user']['avatar'];
            $data[$key]['nickname'] = $value['user']['nickname'];
            $data[$key]['user_id'] = $value['user']['id'];
            $data[$key]['type'] = $value['type'];
            if ($value['type'] == 1){
                $data[$key]['type_text'] = 'CB';
            }else{
                $data[$key]['type_text'] = 'CC';
            }
            $data[$key]['one_price'] = $value['one_price'];
            $data[$key]['num'] = $value['num'];
        }
        $this->success('ok',$data);
    }

    /**
     * 点击-卖出
     */
    public function click_sell(){
        $buy_id = input('buy_id') ? input('buy_id'):$this->error('未指定卖单');
        $type = input('type') ? input('type') : $this->error('未指定类型');//1=cb,2=cc
        if (!in_array($type,['1','2'])){
            $this->error('别瞎指定啊');
        }
        if($type == 1){
            $res = db('config')->where('name','cb_trade')->value('value');
            if (!$res){
                $this->error('交易未开始');
            }

        }else{
            $res = db('config')->where('name','cc_trade')->value('value');
            if (!$res){
                $this->error('交易未开始');
            }
        }
        $buy = db('buy')
            ->where('id',$buy_id)//指定买单
            ->where('type',$type)//指定类型
            ->where('status','1')
            ->find();
        if(!$buy){
            $this->error('订单失效或被他人匹配');
        }
        $user = $this->auth->getUser();
        if ($user->is_truename == 1){
            $this->error('请先通过实名验证');
        }
        $res = db('order')
            ->where('buy_user_id|sell_user_id',$user->id)
            ->where('type',$type)
            ->where('status','in','1,2,4,5')
            ->find();
        if ($res){
            $this->error('存在交易中的订单,暂不可卖出');
        }
        $pay_pwd = input('pay_pwd') ? input('pay_pwd') :'';
        if ($user->paypass != md5(md5($pay_pwd).$user->salt)){
            $this->error('支付密码错误');
        }

        //判断可用数量,手续费
        if($user->is_vot == 1){
            //未复投
            $fee = db('config')->where('name','no_vot_fee')->value('value');
        }else{
            //已复投
            $fee = db('config')->where('name','vot_fee')->value('value');
        }
        $feenum = $fee/100 * $buy['num'];//手续费
        $neednum = $feenum + $buy['num'];//总需
        if ($type == 1){
            if ($user->cb_num < $neednum){
                $this->error('可用数量不足');
            }
        }else{
            if ($user->cc_num < $neednum){
                $this->error('可用数量不足');
            }
        }

        $overtime = db('config')->where('name','overtime')->value('value');//超时时间/h
        Db::startTrans();
        try {
            if ($type == 1){
               $user->cb_num -= $neednum;
               $user->cb_freeze += $neednum;
               $user->save();
                setCbwater($user->id,$neednum,2,'交易卖出'.$buy['num'].'手续费'.$feenum);//记录流水
                add_cb_fee_water($user->id,$feenum);//记录手续费

            }else{
                $user->cc_num -= $neednum;
                $user->cc_freeze += $neednum;
                $user->save();
                setCcwater($user->id,$neednum,2,'交易卖出'.$buy['num'].'手续费'.$feenum);//记录流水
                add_cc_fee_water($user->id,$feenum);//记录手续费
            }
            $price = db('cb_price')->order('id DESC')->find();
            $to_cny = db('config')->where('name','to_cny')->value('value');
            $price = round($price['price'] * $to_cny /100,2);

            db('buy')
                ->where('id',$buy_id)
                ->update(['status'=>2,'updatetime'=>time(),'one_price'=>$price]);//订单锁定
            $order = [];
            $order['buy_user_id'] = $buy['user_id'];//买家
            $order['sell_user_id'] = $user->id;
            $order['buy_id'] = $buy_id;
            $order['type'] = $type;
            $order['one_price'] = $price;//交易单价
            $order['num'] = $buy['num'];
            $order['createtime'] = time();
            $order['overtime'] = $order['createtime'] + $overtime * 3600;//超时时间
            $order['status'] = 1;//买家待付款
            $order['all_freeze'] = $neednum;
            $order_id = db('order')->insertGetId($order);
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success('ok',$order_id);
    }

    /**
     * 获取订单信息
     */
    public function get_order_info(){
        $order_id = input('order_id') ? input('order_id') :$this->error('未指定订单');
        $order = model('order')
            ->with('buyuser')
            ->with('selluser')
            ->where('id',$order_id)
            ->find();
        if (!$order){
            $this->error('订单指定错误');
        }
        $user = $this->auth->getUser();
        if ($user->is_truename == 1){
            $this->error('请先通过实名验证');
        }
        $data = [];
        $list = [];
        if ($order['sell_user_id'] == $user->id ){
            //自己是卖家
            $list[] = ['name'=>'姓名','value'=>$order['buyuser']['nickname']];
            $list[] = ['name'=>'电话','value'=>$order['buyuser']['mobile']];
        }
        $list[] = ['name'=>'币种','value'=> $order['type'] == 1 ? 'CB': 'CC'];
        $list[] = ['name'=>'单价','value'=>$order['one_price']];
        $list[] = ['name'=>'数量','value'=>$order['num']];
        $list[] = ['name'=>'匹配时间','value'=>date('Y/m/d H:i:s',$order['createtime'])];
        $list[] = ['name'=>'剩余时间','value'=>changeTimeType(time()-$order['overtime'])];
        $list[] = ['name'=>'总价(CNY)','value'=>round($order['one_price'] * $order['num'])];
        $data['first']['pay_images'] = explode(',',$order['pay_images']);//付款凭证
        $data['first']['title'] = '订单信息';//付款凭证
        $data['first']['list'] = $list;

        $list = [];
        if ($order['sell_user_id'] == $user->id ){
            //自己是卖家
            $data['second']['title'] = '我的信息';
            $data['second']['pay_images'] = [$user->alipay_image,$user->wechat_image];
            $list[] = ['name'=>'名称','value'=>$user->nickname];
            $list[] = ['name'=>'姓名','value'=>db('user_realname')->where('user_id',$user->id)->where('status','2')->value('truename')];
            $list[] = ['name'=>'电话','value'=>$user->mobile];
//            $list[] = ['name'=>'银行卡号','value'=>$user->bank_num];
//            $list[] = ['name'=>'开户行','value'=>$user->bank_name];
        }else{
            $data['second']['title'] = '卖家信息';
            $data['second']['pay_images'] = [$order['selluser']['alipay_image'],$order['selluser']['wechat_image']];
            $list[] = ['name'=>'名称','value'=>$order['selluser']['nickname']];
            $list[] = ['name'=>'姓名','value'=>db('user_realname')->where('user_id',$order['sell_user_id'])->where('status','2')->value('truename')];
            $list[] = ['name'=>'电话','value'=>$order['selluser']['mobile']];
            $list[] = ['name'=>'银行卡号','value'=>$order['selluser']['bank_num']];
            $list[] = ['name'=>'开户行','value'=>$order['selluser']['bank_name']];
        }
        $data['second']['list'] = $list;
        if ($order['status'] == 1){
            //待付款
            if($order['buy_user_id'] == $user->id){
                $data['operate']['msg'] = '我已付款';
                $data['operate']['type'] = 1;
            }else{
                $data['operate']['msg'] = '等待买家付款';
                $data['operate']['type'] = 2;
            }
            $data['appeal'] = true;
        }elseif($order['status'] == 2){
            //代收款
            if($order['buy_user_id'] == $user->id){
                $data['operate']['msg'] = '等待卖家收款';
                $data['operate']['type'] = 3;
            }else{
                $data['operate']['msg'] = '确认收款';
                $data['operate']['type'] = 4;
            }
            $data['appeal'] = true;
        }else{
            //没其他操作
            $data['operate']['msg'] = '';
            $data['operate']['type'] = 0;
            $data['appeal'] = false;
        }
        $this->success('ok',$data);
    }

    /**
     * 我已付款
     */
    public function me_pay_ok(){
        $order_id = input('order_id') ? input('order_id') : $this->error('未指定订单');
        $pay_images = input('pay_images') ? input('pay_images') :$this->error('未上传付款凭证');
        $user = $this->auth->getUser();
        if ($user->is_truename == 1){
            $this->error('请先通过实名验证');
        }
        if (!$pay_images){
            $this->error('请上传付款凭证');
        }
        $order = db('order')
            ->where('buy_user_id',$user->id)
            ->where('id',$order_id)
            ->where('status','1')
            ->find();
        if (!$order){
            $this->error('该订单暂不可付款,请刷新');
        }
        $overtime = db('config')->where('name','overtime')->value('value');//超时时间/h
        db('order')
            ->where('id',$order_id)
            ->update(['pay_images'=>$pay_images,'updatetime'=>time(),'status'=>2,'overtime'=>time() + $overtime*3600]);
        $this->success('请等待卖家确认');
    }
    /**
     * 确认收款
     */
    public function enter_pay_ok(){
        $order_id = input('order_id') ? input('order_id') : $this->error('未指定订单');
        $user = $this->auth->getUser();
        if ($user->is_truename == 1){
            $this->error('请先通过实名验证');
        }
        $order = db('order')
            ->where('sell_user_id',$user->id)
            ->where('id',$order_id)
            ->where('status','2')
            ->find();
        if (!$order){
            $this->error('该订单暂不可收款,请刷新');
        }
        db('order')->where('id',$order_id)->update(['updatetime'=>time(),'status'=>3]);
        if ($order['type'] == 1){
            //cb
            db('user')->where('id',$order['buy_user_id'])->setInc('cb_num',$order['num']);
            setCbwater($order['buy_user_id'],$order['num'],1,'买入成功');

            db('user')->where('id',$order['sell_user_id'])->setDec('cb_freeze',$order['all_freeze']);


        }else{
            //cc
            db('user')->where('id',$order['buy_user_id'])->setInc('cc_num',$order['num']);
            setCbwater($order['buy_user_id'],$order['num'],1,'买入成功');

            db('user')->where('id',$order['sell_user_id'])->setDec('cc_freeze',$order['all_freeze']);
        }

        $this->success('收款成功');
    }

    /**
     * 委托管理列表
     */
    public function entrust(){
        $type = input('type') ? input('type') : $this->error('未指定类型');//1=cb,2=cc
        $style = input('style') ? input('style') : $this->error('未指定列表类');//1=委托中,2=交易中,3=历史委托
        $page = input('page') ? input('page') : 1;
        $limit = input('limit') ? input('limit') : 10;
        if (!in_array($type,['1','2'])){
            $this->error('别瞎指定啊');
        }
        $user = $this->auth->getUser();
        if ($user->is_truename == 1){
            $this->error('请先通过实名验证');
        }
        if ($style == 1){
            //委托中
            $list = db('buy')
                ->field('id,type,one_price,num')
                ->where('type',$type)
                ->where('user_id',$user->id)//自己的
                ->where('status','1')//委托中
                ->page($page,$limit)
                ->select();
            foreach ($list as $key => $value){
                if(!$value['one_price']){
                    $pricess = db('cb_price')->order('id DESC')->find();
                    $to_cny = db('config')->where('name','to_cny')->value('value');
                    $pricess = round($pricess['price'] * $to_cny /100,2);
                    $list[$key]['one_price'] =$pricess;
                }
                $list[$key]['type_text'] = $value['type'] == 1 ? 'CB': 'CC';
            }
        }elseif ($style == 2){
            //交易中
            $list = db('order')
                ->field('id,type,one_price,buy_user_id,sell_user_id,overtime,status')
                ->where('type',$type)
                ->where('buy_user_id|sell_user_id',$user->id)//自己的
                ->where('status','in','1,2,4,5')//待付款/代收款
                ->page($page,$limit)
                ->select();
            foreach ($list as $key => $value){
                $list[$key]['type_text'] = $value['type'] == 1 ? 'CB': 'CC';


                if($value['status'] == 1){
//                    $list[$key]['overtime_num'] = changeTimeType($value['overtime'] - time())*1000;
//                    $list[$key]['overtime'] = '进行中';
                    $list[$key]['overtime_num'] = 0;
                    $list[$key]['overtime'] = date('Y-m-d H:i:s',$value['overtime']);
                    //买家待付款
                    if ($value['buy_user_id'] == $user->id){
                        //自己没付款
                        $list[$key]['operate_text'] = '付款';
                    }else{
                        $list[$key]['operate_text'] = '待买家付款';
                    }
                }elseif ($value['status'] == 2){
//                    $list[$key]['overtime_num'] = changeTimeType($value['overtime'] - time()) *1000;
//                    $list[$key]['overtime'] = '进行中';
                    $list[$key]['overtime_num'] = 0;
                    $list[$key]['overtime'] = date('Y-m-d H:i:s',$value['overtime']);
                    //卖家收款中
                    if ($value['sell_user_id'] == $user->id){
                        //自己没收款
                        $list[$key]['operate_text'] = '收款';
                    }else{
                        $list[$key]['operate_text'] = '待卖家收款';
                    }
                }elseif($value['status'] == 4){
                    $list[$key]['overtime_num'] = 0;
                    $list[$key]['overtime'] = '申诉中';
                    //买家申诉
                    if ($value['buy_user_id'] == $user->id){
                        //自己申诉
                        $list[$key]['operate_text'] = '申诉中';
                    }else{
                        $list[$key]['operate_text'] = '买家申诉';
                    }
                }else{
                    $list[$key]['overtime_num'] = 0;
                    $list[$key]['overtime'] = '申诉中';
                    //卖家申诉
                    if ($value['sell_user_id'] == $user->id){
                        //自己申诉
                        $list[$key]['operate_text'] = '申诉中';
                    }else{
                        $list[$key]['operate_text'] = '卖家申诉';
                    }
                }

            }
        }elseif ($style == 3){
            //历史委托
            $list = db('order')
                ->field('id,type,one_price,num')
                ->where('type',$type)
                ->where('buy_user_id|sell_user_id',$user->id)//自己的
                ->where('status','3')//完成
                ->page($page,$limit)
                ->select();
            foreach ($list as $key => $value){
                $list[$key]['type_text'] = $value['type'] == 1 ? 'CB': 'CC';
            }
        }else{
            $this->error('别瞎指定啊');
        }
        $this->success('ok',$list);
    }

    /**
     * 取消挂买订单
     */
    public function gobackbuy(){
        $buy_id = input('buy_id') ? input('buy_id') :$this->error('未指定买单');
        $user = $this->auth->getUser();
        if ($user->is_truename == 1){
            $this->error('请先通过实名验证');
        }
        $buy = db('buy')
            ->where('id',$buy_id)
            ->where('user_id',$user->id)
            ->where('status','1')
            ->find();

        $cancel_gua = db('config')->where('name','cancel_gua')->value('value');
        if (!$buy){
            $this->error('该订单不可取消');
        }
        if ($buy['createtime'] + $cancel_gua * 3600 > time()){
            $this->error('挂单'.$cancel_gua.'小时内,不可撤单');
        }
        db('buy')->where('id',$buy_id)->update(['status'=>3,'updatetime'=>time()]);
        $this->success('取消成功');
    }

    /**
     * 求购弹出款信息(指导价)
     */
    public function want_buy_info(){
        $type = input('type') ? input('type') : $this->error('未指定类型');//1=cb,2=cc
        if ($type == 1){
            $info = db('cb_price')->order('id DESC')->find();
        }elseif ($type == 2){
            $info = db('cc_price')->order('id DESC')->find();
        }else{
            $this->error('别瞎指定啊');
        }
        $to_cny = db('config')->where('name','to_cny')->value('value');
        $price = round($info['price'] * $to_cny /100,2);
        $this->success('ok',$price);
    }

    /**
     * 委托买入(求购)
     */
    public function want_buy_buy(){

        $num = input('num') ? input('num') : $this->error('请输入数量');
        $bei = input('bei') ? input('bei') : 1;
        $one_price = input('price') ? input('price'): null;
        $type = input('type') ? input('type') : $this->error('未指定类型');
        if ($num < 0) {
             $this->error('数量不能小于0');
        }
        $num = (int) $num;
        if (!is_int($num)){
            $this->error('数量只能是整数');
        }
        if ($bei < 1 || $bei > 10){
            $this->error('倍数在1-10之间');
        }
        if(!in_array($type,['1','2'])){
            $this->error('别瞎指定啊');
        }
        if($type  == 1){
            $open = db('config')->where('name','cb_buy_switch')->value('value');
        }else{
            $open = db('config')->where('name','cc_buy_switch')->value('value');
        }
        if ($open == 0){
            $this->error('委托通道关闭');
        }
        if ($type == 2){
            $price = db('cc_price')->order('id DESC')->find();
            $to_cny = db('config')->where('name','to_cny')->value('value');
            $price = round($price['price'] * $to_cny /100,2);
            $one_price = round($bei * $price,2);
        }
        $user = $this->auth->getUser();
        $resing = db('order')
            ->where('buy_user_id|sell_user_id',$user->id)
            ->where('type',$type)
            ->where('status','in','1,2,4,5')
            ->count();//正在进行的订单
        $resbuy = db('buy')
            ->where('user_id',$user->id)
            ->where('type',$type)
            ->where('status','1')
            ->count();
//        echo 1;die();
        if ($resbuy + $resing >= 3 ){
            $this->error('最多存在3条进行中的委托和订单');
        }
        if ($user->is_truename == 1){
            $this->error('请先通过实名验证');
        }
        $data = [];
        $data['user_id'] = $user->id;
        $data['num'] = $num;
        $data['createtime'] = time();
        $data['one_price'] = $one_price;
        $data['type'] = $type;
        db('buy')->insert($data);
        $this->success('委托成功');
    }

    /**
     * 下拉范围框
     */
    public function downsearch(){
        $list = db('down_search')->order('min ASC')->select();
        $data = [];
        foreach ($list as $key => $value){
            $data[$key] = $value['min'].' - '.$value['max'];
        }
        $this->success('ok',$data);
    }
}